package com.gree.kundada.intercepter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.gree.kundada.common.BaseResponse;
import com.gree.kundada.common.ResultUtils;
import com.gree.kundada.model.entity.CurrentUser;
import com.gree.kundada.utils.AuthContextUtil;
import com.gree.kundada.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

import static com.gree.kundada.common.ErrorCode.NOT_LOGIN_ERROR;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate redisTemplate ;

    @Autowired
    private TokenUtils tokenUtils;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        // 获取请求方式
        String method = request.getMethod();
        if("OPTIONS".equals(method)) {      // 如果是跨域预检请求，直接放行
            return true ;
        }
        
        // 获取token
        String token = request.getHeader("Authorization");
        if(StrUtil.isEmpty(token) || token.length() < 7) {
            responseNoLoginInfo(response) ;
            return false ;
        }
        token = token.substring(7);
        // 如果token不为空，那么此时验证token的合法性
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        // redis中token是否存在
        if (Boolean.FALSE.equals(redisTemplate.hasKey("kundada:user:"+currentUser.getUserAccount()))) {
            responseNoLoginInfo(response);
            return false;
        }
        String redisToken = redisTemplate.opsForValue().get("kundada:user:" + currentUser.getUserAccount());
        if(StrUtil.isEmpty(redisToken)) {
            responseNoLoginInfo(response);
            return false;
        }
        if (!redisToken.equals(token)) {
            responseNoLoginInfo(response);
            return false;
        }

        // 将用户数据存储到ThreadLocal中
        AuthContextUtil.set(currentUser);

        // 重置Redis中的用户数据的有效时间
        redisTemplate.expire("kundada:user:" + currentUser.getUserAccount() , 30 , TimeUnit.MINUTES) ;

        // 放行
        return true ;
    }

    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        BaseResponse result = ResultUtils.error(NOT_LOGIN_ERROR);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();  // 移除threadLocal中的数据
    }
}